
const { exec, spawn } = require('child_process');
const {createGzip} = require('zlib');
const fs = require('fs')

const compressing = require('compressing');

const cmdRun = (command)=>{
    return new Promise((resolve, rejects)=>{
        if(command) {
          console.log(`开始执行：${command}`)
          const execRuner = exec(command,{ encoding: "buffer" }, function (error, stdout, stderr) {
              if (error) {
                console.log(`执行的错误: ${error}`)
                return;
              }else if (stderr) {
                console.log(`标准错误输出: ${stderr}`)
              }
              console.log(`命令的输出结果：\n${stdout}`)
            });
          execRuner.on('exit', function (code) {
            console.log(`命令${command} 执行结束： ${code}`)
            resolve()
          })
        }
    })
  }

  function gzipFile (sourcePath, target){
    return new Promise((resolve, reject)=>{
      
      const gzip = createGzip();
      const rs = fs.createReadStream(sourcePath);
      const ws = fs.createWriteStream(target);
      // pipeline(rs, gzip, ws, (err) => {
      //   if (err) {
      //       process.exitCode = 1;
      //   } else {
      //       // // 将文件名改回去
      //       // fs.renameSync(destPath, srcPath);
      //       // console.log('gz:' ,targetpath);
      //       console.log('文件替换完gzip成功: ', targetpath);
      //   }
      //   resolve()
      // });
      rs.pipe(gzip).pipe(ws);
      ws.on('finish', resolve);
      ws.on('error', reject);
      rs.on('error', reject);
      gzip.on('error', reject);
    })
  }
  function zipDirtory(sourcePath, target) {
    compressing.zip.compressDir(sourcePath, target)
  }
  module.exports = {
    cmdRun,
    gzipFile,
    zipDirtory
  }